package com.tdam2011.grupo06.gui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tdam2011.grupo06.R;
import com.tdam2011.grupo06.control.DatabaseHelper;
import com.tdam2011.grupo06.control.GestorHistorial;
import com.tdam2011.grupo06.gui.PullToRefreshListView.OnRefreshListener;
import com.tdam2011.grupo06.model.Contacto;
import com.tdam2011.grupo06.model.ItemEmail;
import com.tdam2011.grupo06.model.ItemHistorial;
import com.tdam2011.grupo06.model.Llamada;
import com.tdam2011.grupo06.model.Mensaje;
import com.tdam2011.grupo06.model.MensajeBob;

public class ListadoHistorial extends ListActivity
{
	private LinearLayout linearLay;
	private ItemHistorialAdapter adapter;
	private CargarHistorialTask cargarHistorialTask;
	private GestorHistorial gestorHistorial;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lista_historial);
		adapter = new ItemHistorialAdapter();
		gestorHistorial = new GestorHistorial(this);
		linearLay = (LinearLayout) findViewById(R.id.linearLayoutListaHistorial);
		setListAdapter(adapter);
		registerForContextMenu(getListView());
		
		// Set a listener to be invoked when the list should be refreshed.
		((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
		    @Override
		    public void onRefresh() {
		    	if(cargarHistorialTask!=null){
		    		cargarHistorialTask.cancel(true);
		    	}
		    	cargarHistorialTask = new CargarHistorialTask();
		    	cargarHistorialTask.execute("");
		    }
		});
		((PullToRefreshListView) getListView()).onRefresh();
	}
	
	public class ItemHistorialAdapter extends BaseAdapter 
	{
		private ArrayList<ItemHistorial> itemsHistorial;
		private ArrayList<Contacto> contactos;
		private LayoutInflater inflater;
		private int cantTel;
		private int cantMenSms;
		private int cantMenMms;
		private int cantMail;
		private int cantBorr;
		private int cantMensajesBob;

		public ItemHistorialAdapter() 
		{
			itemsHistorial = new ArrayList<ItemHistorial>();
			contactos = new ArrayList<Contacto>();
			inflater = LayoutInflater.from(ListadoHistorial.this);
			cantTel = 0;
			cantMenSms = 0;
			cantMenMms = 0;
			cantMail = 0;
			cantMensajesBob = 0;
			cantBorr = 0;
		}

		public void addItemInfo(ItemHistorial info) {
			if (info != null) {
				itemsHistorial.add(info);
				
				if(info instanceof Llamada) {cantTel++;}
				else if(info instanceof Mensaje) 
				{
					if(((Mensaje)info).getSubtipo()==1){cantMenSms++;}
					else {cantMenMms++;}
				}
				else if(info instanceof ItemEmail) {cantMail++;}
				else if(info instanceof MensajeBob) {cantMensajesBob++;}
			}
		}
		
		public void addContacto(Contacto info) {
			if (info != null) {
				contactos.add(info);
			}
		}

		public int getCount() {
			return itemsHistorial.size();
		}

		public Object getItem(int position) {
			return itemsHistorial.get(position);
		}

		public long getItemId(int position) {
			return position;
		}
		
		public Contacto getContactoById(int id) 
		{
			Iterator<Contacto> iter = contactos.iterator();
			Contacto aux;
			while (iter.hasNext())
			{
				aux = iter.next();
				if(aux.getDbId()==id)
				{
					return aux; 
				}
			}
			return null;
		}
		
		public void ordenarHistorial(Comparator<ItemHistorial> c)
		{
			if(itemsHistorial.size()!=0)
			{
				Collections.sort(itemsHistorial, c);
			}
		}
		
		public int getCantTel()
		{
			return cantTel;
		}
		
		public int getCantMenSms()
		{
			return cantMenSms;
		}
		
		public int getCantMenMms() 
		{
			return cantMenMms;
		}
		
		public int getCantEmail()
		{
			return cantMail;
		}
		
		public int getCantMensajesBob() 
		{
			return cantMensajesBob;
		}
		
		public int getCantBorr()
		{
			return cantBorr;
		}
		
		public void addBorr()
		{
			cantBorr++;
		}

		public void emptyLists()
		{
			itemsHistorial.clear();
			contactos.clear();
			cantTel = 0;
			cantMenSms = 0;
			cantMenMms = 0;
			cantMail = 0;
			cantMensajesBob = 0;
			cantBorr = 0;
		}
		
		class Holder 
		{
			private ImageView imgContacto;
			private TextView txtNombre;
			private TextView txtTel;
			private ImageView imgTipo;
			private TextView txtFecha;
			private ImageView imgSubTipo;
		}

		public View getView(int position, View convertView, ViewGroup arg2) 
		{
			Holder holder;
			if (convertView == null) 
			{
				convertView = inflater.inflate(R.layout.item_historial, null);
				holder = new Holder();
				holder.imgContacto = (ImageView) convertView.findViewById(R.id.imageViewHistorialContacto);
				holder.txtNombre = (TextView) convertView.findViewById(R.id.txtHistorialNombre);
				holder.txtTel = (TextView) convertView.findViewById(R.id.txtHistorialNumero);
				holder.imgTipo = (ImageView) convertView.findViewById(R.id.imageViewHistorialTipo);
				holder.txtFecha = (TextView) convertView.findViewById(R.id.txtHistorialFecha);
				holder.imgSubTipo = (ImageView) convertView.findViewById(R.id.imageViewHistorialSubTipo);
				convertView.setTag(holder);
			} 
			else 
			{
				holder = (Holder) convertView.getTag();
			}

			ItemHistorial info = (ItemHistorial) getItem(position);
			Contacto aux = getContactoById(info.getIdContacto());
			
			if(aux==null)
			{
				holder.imgContacto.setImageDrawable(getResources().getDrawable(R.drawable.ic_contact));
				holder.txtNombre.setText(info.getNumero());
			}
			else
			{
				holder.imgContacto.setImageURI(aux.getPhotoUri());
				holder.txtNombre.setText(aux.getNombre());
			}
			holder.txtTel.setText(info.getNumero());
			holder.txtFecha.setText(info.getFechaString());
			
			if(info instanceof Llamada)
			{
				holder.imgTipo.setImageDrawable(getResources().getDrawable(R.drawable.ic_realizar_llamada));
			}
			else if (info instanceof Mensaje)
			{
				holder.imgTipo.setImageDrawable(((Mensaje) info).getSubtipoDrawable(ListadoHistorial.this));
			}
			else if (info instanceof ItemEmail)
			{
				holder.imgTipo.setImageDrawable(getResources().getDrawable(R.drawable.ic_realizar_email));
			}
			else if (info instanceof MensajeBob)
			{
				holder.txtTel.setText(((MensajeBob) info).getUsuario());
				holder.imgTipo.setImageDrawable(getResources().getDrawable(R.drawable.ic_realizar_mensaje_web_c));
			}
			holder.imgSubTipo.setImageDrawable(info.getTipoDrawable(ListadoHistorial.this));
			return convertView;
		}
	}
	
	@Override
	protected void onResume() 
	{
		super.onResume();
	}

	@Override
	protected void onPause() 
	{
		super.onPause();
	}

	@Override
	protected void onStop() 
	{
		super.onStop();
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) 
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Acciones de historial");
		menu.add(0, ((AdapterView.AdapterContextMenuInfo)menuInfo).position, 1, "Eliminar item");
	}
	
	public boolean onContextItemSelected(MenuItem item) 
	{
		switch(item.getOrder())
		{
			case 1:
				ItemHistorial itemHistorial = (ItemHistorial) adapter.getItem(item.getItemId()-1);
				if(itemHistorial instanceof MensajeBob || itemHistorial instanceof ItemEmail){
					DatabaseHelper.getInstance(this).eliminarItemHistorial(itemHistorial);
				}
				else{
					gestorHistorial.deleteItemHistorial(itemHistorial);
				}
				Toast.makeText(this, "Item historial eliminado",Toast.LENGTH_SHORT).show();
				gestorHistorial.actualizar();
				((PullToRefreshListView) getListView()).onRefresh();
				return true;
			default:
				return super.onContextItemSelected(item);
		}
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    menu.add(Menu.NONE, 1, Menu.NONE, "Preferencias");
	    menu.add(Menu.NONE, 2, Menu.NONE, "Filtrar por");
	    SubMenu smnuOrd = menu.addSubMenu(Menu.NONE, Menu.NONE, Menu.NONE, "Ordenar por");
	    smnuOrd.add(Menu.NONE, 3, 1, "Nombre ascendente");
	    smnuOrd.add(Menu.NONE, 3, 2, "Nombre descendente");
	    smnuOrd.add(Menu.NONE, 3, 3, "Fecha ascendente");
	    smnuOrd.add(Menu.NONE, 3, 4, "Fecha descendente");
	    smnuOrd.add(Menu.NONE, 3, 5, "Tipo ascendente");
	    smnuOrd.add(Menu.NONE, 3, 6, "Tipo descendente");
	    smnuOrd.setGroupCheckable(Menu.NONE, true, true);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    switch (item.getItemId()) 
	    {
	        case 1:
	        	startActivity(new Intent(this, SetPreferenceNombreUsuario.class).putExtra("NoInicio", true));
	            return true;
	        case 2:
	        	startActivityForResult(new Intent(this, SetPreferenceFiltrarHistorial.class),0);
	            return true;
	        case 3:
	        	SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
	        	SharedPreferences.Editor editor = myPreference.edit();
	        	String[] order = getResources().getStringArray(R.array.ordenamietoHistorial);
	        	switch (item.getOrder()) 
	    	    {
	    	        case 1:
	    	        	editor.putString("ordenamietoHistorial", order[0]);
	    	        	adapter.ordenarHistorial(ItemHistorial.comparadorNombreAsc);
	    	            break;
	    	        case 2:
	    	        	editor.putString("ordenamietoHistorial", order[1]);
	    	        	adapter.ordenarHistorial(ItemHistorial.comparadorNombreDesc);
	    	            break;
	    	        case 3:
	    	        	editor.putString("ordenamietoHistorial", order[2]);
	    	        	adapter.ordenarHistorial(ItemHistorial.comparadorFechaAsc);
	    	            break;
	    	        case 4:
	    	        	editor.putString("ordenamietoHistorial", order[3]);
	    	        	adapter.ordenarHistorial(ItemHistorial.comparadorFechaDesc);
	    	            break;
	    	        case 5:
	    	        	editor.putString("ordenamietoHistorial", order[4]);
	    	        	adapter.ordenarHistorial(ItemHistorial.comparadorTipoAsc);
	    	            break;
	    	        case 6:
	    	        	editor.putString("ordenamietoHistorial", order[5]);
	    	        	adapter.ordenarHistorial(ItemHistorial.comparadorTipoDesc);
	    	            break;
	    	    }
	        	adapter.notifyDataSetChanged();
	            return editor.commit();
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		SubMenu smnuOrd = menu.getItem(2).getSubMenu();
		SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
    	String[] order = getResources().getStringArray(R.array.ordenamietoHistorial);
    	String orden = myPreference.getString("ordenamietoHistorial", "");
    	for (int i = 0; i<order.length; i++)
    	{
    		if(order[i].compareTo(orden)==0)
    		{
    			smnuOrd.getItem(i).setChecked(true);
    		}
    	}
	    return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0) 
		{
			if (data!=null)
			{
				gestorHistorial.actualizar();
				((PullToRefreshListView) getListView()).onRefresh();
			}
		}
	}
	
	private class CargarHistorialTask extends AsyncTask<String, Void, ItemHistorialAdapter>
	{
		@Override
		protected ItemHistorialAdapter doInBackground(String... params) 
		{
			boolean flag = gestorHistorial.verificarHistorial(adapter);
			
			if(flag)
			{
				adapter.emptyLists();
				return gestorHistorial.cargarHistorial(adapter);
			}
			return null;
		}
		
		protected void onPostExecute(ItemHistorialAdapter result)
		{
			if(result!=null)
			{
				adapter = result;
				adapter.notifyDataSetChanged();
			}

			if(linearLay.getVisibility()!=View.GONE){
	    		linearLay.setVisibility(View.GONE);
	    	}
			if(adapter.isEmpty()){
    			((PullToRefreshListView) getListView()).onRefreshComplete(getResources().getString(R.string.empty_listHistorial));
    		}
    		else{
    			((PullToRefreshListView) getListView()).onRefreshComplete(null);
    		}
	        super.onPostExecute(result);
		}
	}
	
	protected Dialog onCreateDialog(int id) 
	{
		Dialog dialog = null;
		if (id ==1) 
		{
			dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_alert).setPositiveButton("Ok", null).setMessage("Todavia no se ha cargado el historial").setTitle("Error").create();;
		} 
		else 
		{
			dialog = super.onCreateDialog(id);
		}
		return dialog;
	}
	
	@Override
	public void onBackPressed() 
	{
		super.onBackPressed();
	}
}
